package com.yxq.mdt.app.modules.personal.adapter;

import android.content.Intent;
import android.graphics.Color;
import android.os.CountDownTimer;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.text.style.ForegroundColorSpan;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.blankj.utilcode.util.TimeUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.yxq.mdt.app.R;
import com.yxq.mdt.app.glide.GlideHelper;
import com.yxq.mdt.app.modules.personal.bean.PublishBean;
import com.yxq.mdt.app.modules.picturebrowse.ui.PictureActivity;
import com.yxq.mdt.app.modules.socialcontact.adapter.SocialStateContactAdapter;
import com.yxq.mdt.app.modules.socialcontact.bean.MainSocialContactBean;
import com.yxq.mdt.app.modules.socialcontact.bean.SocialStateContactBean;
import com.yxq.mdt.app.modules.socialcontact.ui.activity.CircleTopicAc;
import com.yxq.mdt.app.utils.GridSpacingItemDecoration;
import com.yxq.mdt.app.utils.MediaPlayerHelper;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import cn.jzvd.Jzvd;
import cn.jzvd.JzvdStd;

/**
 * @author L
 * @time
 * @describe 我的帖子列表
 */
public class DynamicListAdapter extends BaseQuickAdapter<PublishBean.ListBean, BaseViewHolder> {

    private String content = "";
    private String contentTv = "";
    SpannableStringBuilder spannableStringBuilder;
    public CountDownTimer countDownTimer;
    public boolean isVoiceStart = false;

    public DynamicListAdapter(int layoutResId, @Nullable List<PublishBean.ListBean> data) {
        super(layoutResId, data);
    }

    @Override
    protected void convert(BaseViewHolder helper, PublishBean.ListBean item) {
        int len = 0;
        int audioLen = 0;
        helper.addOnClickListener(R.id.item_layout_nike_img);
        helper.addOnClickListener(R.id.item_layout_content_delete);
        ImageView avatar = helper.getView(R.id.item_layout_nike_img);
        RecyclerView recyclerView = helper.getView(R.id.item_layout_content_recyclerView);
        JzvdStd jzvdStd = helper.getView(R.id.item_social_video_player);
        LinearLayout lint = helper.getView(R.id.item_social_lint);
        TextView textView = helper.getView(R.id.item_tv_subject);
        LinearLayout voice = helper.getView(R.id.publish_save_voice);
        ImageView voiceNote = helper.getView(R.id.publish_note);
        TextView voiceTime = helper.getView(R.id.publish_add_voice_time);

        contentTv = item.getContent();

        if (item.getContent() != null && item.getContent().contains("#")) {
            content = (item.getContent().substring(item.getContent().indexOf("#"), item.getContent().lastIndexOf("#") + 1));
        } else {
            content = item.getContent();
        }
        spannableStringBuilder = new SpannableStringBuilder("");

        if (!TextUtils.isEmpty(contentTv)) {
            spannableStringBuilder.append(contentTv);
        }
        if (item.getContent() != null && item.getContent().contains("#")) {
            ForegroundColorSpan foregroundColorSpan = new ForegroundColorSpan(Color.parseColor("#ffa800"));
            spannableStringBuilder.setSpan(foregroundColorSpan, 0, (item.getContent().substring(item.getContent().indexOf("#"), item.getContent().lastIndexOf("#") + 1)).length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            spannableStringBuilder.setSpan(new ForegroundColorSpan(Color.parseColor("#222222")), (item.getContent().substring(item.getContent().indexOf("#"), item.getContent().lastIndexOf("#") + 1)).length(), spannableStringBuilder.length(), Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
            ClickableSpan clickableSpan = new ClickableSpan() {
                @Override
                public void onClick(@NonNull View view) {
                    Intent it = new Intent(mContext, CircleTopicAc.class);
                    it.putExtra("topicId", item.getId());
                    it.putExtra("topic", (item.getContent().substring(item.getContent().indexOf("#"), item.getContent().lastIndexOf("#") + 1)));
                    mContext.startActivity(it);
                }
            };
            //文本可点击，有点击事件
            spannableStringBuilder.setSpan(clickableSpan, 0, content.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            // 设置此方法后，点击事件才能生效
            textView.setMovementMethod(LinkMovementMethod.getInstance());
            textView.setText(spannableStringBuilder);
        } else {
            helper.setText(R.id.item_tv_subject, item.getContent());
            helper.setTextColor(R.id.item_tv_subject, Color.parseColor("#222222"));
            textView.setTextColor(Color.parseColor("#222222"));
        }
        //超过75个字符就显示全文按钮
        helper.setVisible(R.id.item_tv_subject_all, (textView.getText().length() > 75));
        //昵称
        helper.setText(R.id.item_layout_nike_name, item.getGsName());
        //头像
        GlideHelper.setLoadRoundImage(mContext, item.getHeadimg(), R.mipmap.head_icon, avatar);
        //浏览数
//        helper.setText(R.id.item_tv_count_browse, item.getViewCount() + "次浏览");
        //是否点赞
        if (item.getGiveLike() != 0) {
            helper.setImageResource(R.id.item_layout_content_browse_img, R.mipmap.zan);
        } else {
            helper.setImageResource(R.id.item_layout_content_browse_img, R.mipmap.icon_community_fabulous);
        }
        //点赞数
        if (item.getGiveLike() != 0) {
            helper.setText(R.id.item_layout_content_browse, item.getUpCount() + "");
        } else {
            helper.setText(R.id.item_layout_content_browse, "点赞");
        }
        //评论数
        if (item.getCommentCount() != 0) {
            helper.setText(R.id.item_layout_content_give_like, item.getCommentCount() + "");
        } else {
            helper.setText(R.id.item_layout_content_give_like, "评论");
        }
        helper.addOnClickListener(R.id.item_layout_content_browse_img);
        //发布时间
        helper.setText(R.id.item_layout_time, TimeUtils.getFriendlyTimeSpanByNow(item.getCreateDate(), new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")));
        //性别
        helper.setImageResource(R.id.item_iv_sex, item.getSex() == 1 ? R.mipmap.xb_nan : R.mipmap.xb_nv);
        if (item.getGroupname() != null) {
            helper.setText(R.id.group_name, item.getGroupname());
            GlideHelper.setLoadRoundImage(mContext, item.getLogo(), R.mipmap.head_icon, helper.getView(R.id.item_layout_circle_img));
            helper.setGone(R.id.group_lint, true);
        } else {
            helper.setGone(R.id.group_lint, false);
        }
        //1 图片 2 视频
        if (item.getFileList() != null && item.getFileList().size() > 0 && "1".equals(item.getFileList().get(0).getClass1())) {
            recyclerView.setVisibility(View.VISIBLE);
            lint.setVisibility(View.GONE);
            voice.setVisibility(View.GONE);
            DynamicImagesListAdapter dynamicImagesListAdapter = new DynamicImagesListAdapter(R.layout.item_layout_social_list, item.getFileList());
            recyclerView.setLayoutManager(new GridLayoutManager(mContext, 3));
            recyclerView.setAdapter(dynamicImagesListAdapter);
            dynamicImagesListAdapter.setOnItemClickListener((adapter, view, position) -> {
                Intent intent = new Intent(mContext, PictureActivity.class);
                intent.putExtra("position", position);
                ArrayList<String> images = new ArrayList<>();
                for (PublishBean.ListBean.FileListBean fileListBean : item.getFileList()) {
                    images.add(fileListBean.getFile());
                }
                intent.putExtra("images", images);
                mContext.startActivity(intent);
            });
            if (recyclerView.getItemDecorationCount() == 0) {
                recyclerView.addItemDecoration(new GridSpacingItemDecoration(3, 8, false));
            }
        } else if (item.getFileList() != null && item.getFileList().size() > 0 && "2".equals(item.getFileList().get(0).getClass1())) {
            ImageView imageViewVideo = jzvdStd.thumbImageView;
            imageViewVideo.setScaleType(ImageView.ScaleType.CENTER_CROP);
            GlideHelper.setLoadRoundImage(mContext, item.getFileList().get(0).getFile(), R.color.gray, imageViewVideo);
            jzvdStd.setUp(item.getFileList().get(0).getFile(), "", Jzvd.SCREEN_NORMAL);
            Jzvd.setVideoImageDisplayType(JzvdStd.VIDEO_IMAGE_DISPLAY_TYPE_FILL_SCROP);
            lint.setVisibility(View.VISIBLE);
            recyclerView.setVisibility(View.GONE);
            voice.setVisibility(View.GONE);
        } else if (item.getFileList() != null && item.getFileList().size() > 0 && "6".equals(item.getFileList().get(0).getClass1())) {
            recyclerView.setVisibility(View.GONE);
            lint.setVisibility(View.GONE);
            voice.setVisibility(View.VISIBLE);
            if (item.getFileList() != null && item.getFileList().size() > 0 && item.getFileList().get(0).getClass2() != 0) {
                audioLen = item.getFileList().get(0).getClass2();
                if (audioLen < 1000) {
                    voiceTime.setText(audioLen + "″");
                } else {
                    audioLen = audioLen / 1000;
                    voiceTime.setText(audioLen + "″");
                }
            }
            int finalAudioLen = audioLen;
            voice.setOnClickListener(view -> {
                if (isVoiceStart) {
                    isVoiceStart = false;
                    MediaPlayerHelper.realese();
                    countDownTimer.onFinish();
                } else {
                    isVoiceStart = true;
                    MediaPlayerHelper.playSound(item.getFileList().get(0).getFile(), mediaPlayer -> isVoiceStart = false);
                    getTime(finalAudioLen + "", voiceNote, voiceTime);
                    countDownTimer.start();
                }

            });
        } else {
            //文字
            recyclerView.setVisibility(View.GONE);
            lint.setVisibility(View.GONE);
            voice.setVisibility(View.GONE);
        }
    }

    /**
     * @param playTime  开始时间
     * @param imageView 获取当前控件
     * @param timeTv    获取显示秒数
     */
    private void getTime(String playTime, ImageView imageView, TextView timeTv) {
        imageView.setImageResource(R.mipmap.voice_note_new);
        countDownTimer = new CountDownTimer(Integer.parseInt(playTime) * 1000, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                timeTv.setText(millisUntilFinished / 1000 + "″");
            }

            @Override
            public void onFinish() {
                timeTv.setText(Integer.parseInt(playTime) + "″");
                imageView.setImageResource(R.mipmap.voice_note);
                countDownTimer.cancel();
            }
        };
    }
}
